<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ELM API 调试工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .test-section {
            margin-bottom: 30px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
        }

        .test-section h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.5em;
        }

        .button-group {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
        }

        .btn-info {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
            color: #333;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .result-container {
            margin-top: 20px;
            border-radius: 8px;
            overflow: hidden;
        }

        .result-header {
            background: #f8f9fa;
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
            font-weight: 600;
            color: #495057;
        }

        .result-content {
            padding: 20px;
            background: white;
        }

        .status-success {
            border-left: 4px solid #28a745;
            background: #d4edda;
        }

        .status-error {
            border-left: 4px solid #dc3545;
            background: #f8d7da;
        }

        .business-card {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background: #f8f9fa;
        }

        .business-card h3 {
            color: #495057;
            margin-bottom: 10px;
        }

        .business-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            font-size: 14px;
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .detail-label {
            font-weight: 600;
            color: #6c757d;
        }

        .detail-value {
            color: #495057;
        }

        .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 30px;
            color: #6c757d;
        }

        .loading::before {
            content: '';
            width: 20px;
            height: 20px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .json-viewer {
            background: #2d3748;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 400px;
            overflow-y: auto;
        }

        .toggle-json {
            margin-top: 15px;
        }

        .info-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .badge-success {
            background: #d4edda;
            color: #155724;
        }

        .badge-error {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-info {
            background: #d1ecf1;
            color: #0c5460;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🍽️ ELM API 调试工具</h1>
        <p>快速诊断前后端连接问题</p>
    </div>

    <div class="content">
        <!-- 基础连接测试 -->
        <div class="test-section">
            <h2>🔗 基础连接测试</h2>
            <div class="button-group">
                <button class="btn btn-primary" onclick="testConnection()" id="testConnBtn">测试连接</button>
                <button class="btn btn-info" onclick="testPing()" id="testPingBtn">Ping 后端</button>
            </div>
            <div id="connectionResult"></div>
        </div>

        <!-- 商家API测试 -->
        <div class="test-section">
            <h2>🏪 商家排序API测试</h2>
            <div class="button-group">
                <button class="btn btn-success" onclick="testSort('rating')" id="testRatingBtn">按评分排序</button>
                <button class="btn btn-success" onclick="testSort('distance')" id="testDistanceBtn">按距离排序</button>
                <button class="btn btn-success" onclick="testSort('sales')" id="testSalesBtn">按销量排序</button>
                <button class="btn btn-warning" onclick="testAllMethods()" id="testAllBtn">测试所有方法</button>
            </div>
            <div id="businessResult"></div>
        </div>

        <!-- 数据库状态检查 -->
        <div class="test-section">
            <h2>🗄️ 数据库状态检查</h2>
            <div class="button-group">
                <button class="btn btn-info" onclick="checkBusinessTable()" id="checkTableBtn">检查商家表结构</button>
                <button class="btn btn-info" onclick="testBasicQuery()" id="testQueryBtn">测试基础查询</button>
            </div>
            <div id="databaseResult"></div>
        </div>
    </div>
</div>

<script>
    const API_BASE = 'http://localhost:8080/elm';
    let currentTest = null;

    // 通用的显示结果函数
    function showResult(containerId, status, title, content, data = null) {
        const container = document.getElementById(containerId);
        const statusClass = status === 'success' ? 'status-success' : 'status-error';
        const badgeClass = status === 'success' ? 'badge-success' : 'badge-error';

        let html = `
                <div class="result-container ${statusClass}">
                    <div class="result-header">
                        <span class="info-badge ${badgeClass}">${status.toUpperCase()}</span>
                        ${title}
                    </div>
                    <div class="result-content">
                        ${content}
                        ${data ? `
                            <button class="btn btn-info toggle-json" onclick="toggleJson('${containerId}_json')">
                                显示/隐藏原始数据
                            </button>
                            <div id="${containerId}_json" class="json-viewer" style="display: none;">
                                ${JSON.stringify(data, null, 2)}
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;

        container.innerHTML = html;
    }

    // 显示加载状态
    function showLoading(containerId, message = '正在处理...') {
        const container = document.getElementById(containerId);
        container.innerHTML = `<div class="loading">${message}</div>`;
    }

    // 切换JSON显示
    function toggleJson(id) {
        const element = document.getElementById(id);
        element.style.display = element.style.display === 'none' ? 'block' : 'none';
    }

    // 设置按钮状态
    function setButtonState(buttonId, disabled) {
        const button = document.getElementById(buttonId);
        if (button) {
            button.disabled = disabled;
        }
    }

    // 测试基础连接
    async function testConnection() {
        showLoading('connectionResult', '正在测试连接...');
        setButtonState('testConnBtn', true);

        try {
            const response = await fetch(`${API_BASE}/api/BusinessController/listBusiness`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await response.json();

            if (response.ok) {
                showResult('connectionResult', 'success',
                    '✅ 连接成功',
                    `
                            <p><strong>状态码：</strong>${response.status}</p>
                            <p><strong>响应类型：</strong>${Array.isArray(data) ? 'Array' : typeof data}</p>
                            <p><strong>数据长度：</strong>${Array.isArray(data) ? data.length : 'N/A'}</p>
                            <p><strong>服务器：</strong>${response.headers.get('server') || '未知'}</p>
                        `,
                    data
                );
            } else {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
        } catch (error) {
            showResult('connectionResult', 'error',
                '❌ 连接失败',
                `
                        <p><strong>错误类型：</strong>${error.name}</p>
                        <p><strong>错误信息：</strong>${error.message}</p>
                        <p><strong>可能原因：</strong></p>
                        <ul>
                            <li>后端服务未启动 (检查 http://localhost:8080/elm)</li>
                            <li>端口被占用或配置错误</li>
                            <li>CORS策略阻止</li>
                            <li>网络连接问题</li>
                        </ul>
                    `,
                { error: error.message, stack: error.stack }
            );
        } finally {
            setButtonState('testConnBtn', false);
        }
    }

    // 测试Ping
    async function testPing() {
        showLoading('connectionResult', '正在Ping后端服务...');
        setButtonState('testPingBtn', true);

        try {
            const startTime = Date.now();
            const response = await fetch(`${API_BASE}/api/BusinessController/listBusiness`, {
                method: 'HEAD'
            });
            const endTime = Date.now();
            const duration = endTime - startTime;

            showResult('connectionResult', 'success',
                '🏓 Ping 成功',
                `
                        <p><strong>响应时间：</strong>${duration}ms</p>
                        <p><strong>状态码：</strong>${response.status}</p>
                        <p><strong>服务器状态：</strong>正常运行</p>
                    `
            );
        } catch (error) {
            showResult('connectionResult', 'error',
                '🏓 Ping 失败',
                `
                        <p><strong>错误：</strong>${error.message}</p>
                        <p><strong>建议：</strong>检查后端服务是否启动</p>
                    `
            );
        } finally {
            setButtonState('testPingBtn', false);
        }
    }

    // 测试排序API
    async function testSort(sortType) {
        showLoading('businessResult', `正在测试${sortType}排序...`);
        const buttonId = `test${sortType.charAt(0).toUpperCase() + sortType.slice(1)}Btn`;
        setButtonState(buttonId, true);

        try {
            // 尝试GET方法
            let response = await fetch(`${API_BASE}/api/BusinessController/listBusinessBySort?sortType=${sortType}`);
            let data = await response.json();
            let method = 'GET';

            // 如果GET失败，尝试POST方法
            if (!response.ok) {
                response = await fetch(`${API_BASE}/api/BusinessController/listBusinessBySort`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `sortType=${sortType}`
                });
                data = await response.json();
                method = 'POST';
            }

            if (response.ok && Array.isArray(data)) {
                const businessCards = data.slice(0, 3).map((business, index) => `
                        <div class="business-card">
                            <h3>商家 ${index + 1}: ${business.businessName || '未知'}</h3>
                            <div class="business-details">
                                <div class="detail-item">
                                    <span class="detail-label">商家ID:</span>
                                    <span class="detail-value">${business.businessId || 'N/A'}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">距离:</span>
                                    <span class="detail-value">${business.distance || 0}km</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">月销量:</span>
                                    <span class="detail-value">${business.monthlySales || 0}单</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">评分:</span>
                                    <span class="detail-value">${business.rating || 0}分</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">起送价:</span>
                                    <span class="detail-value">¥${business.starPrice || 0}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">配送费:</span>
                                    <span class="detail-value">¥${business.deliveryPrice || 0}</span>
                                </div>
                            </div>
                        </div>
                    `).join('');

                showResult('businessResult', 'success',
                    `🎉 ${sortType}排序测试成功`,
                    `
                            <p><strong>请求方法：</strong>${method}</p>
                            <p><strong>数据总数：</strong>${data.length} 个商家</p>
                            <p><strong>排序效果：</strong>数据已按${sortType}排序</p>
                            <h4>商家预览 (前3个):</h4>
                            ${businessCards}
                        `,
                    data
                );
            } else {
                throw new Error(`API返回格式错误: ${typeof data}`);
            }
        } catch (error) {
            showResult('businessResult', 'error',
                `❌ ${sortType}排序测试失败`,
                `
                        <p><strong>错误：</strong>${error.message}</p>
                        <p><strong>排序类型：</strong>${sortType}</p>
                        <p><strong>建议检查：</strong></p>
                        <ul>
                            <li>数据库中business表是否存在${sortType}字段</li>
                            <li>后端servlet是否正确处理sortType参数</li>
                            <li>数据库连接是否正常</li>
                        </ul>
                    `,
                { sortType, error: error.message }
            );
        } finally {
            setButtonState(buttonId, false);
        }
    }

    // 测试所有方法
    async function testAllMethods() {
        setButtonState('testAllBtn', true);
        showLoading('businessResult', '正在测试所有排序方法...');

        const results = [];
        const sortTypes = ['rating', 'distance', 'sales'];

        for (const sortType of sortTypes) {
            try {
                const response = await fetch(`${API_BASE}/api/BusinessController/listBusinessBySort?sortType=${sortType}`);
                const data = await response.json();

                results.push({
                    sortType,
                    success: response.ok && Array.isArray(data),
                    count: Array.isArray(data) ? data.length : 0,
                    firstBusiness: Array.isArray(data) && data.length > 0 ? data[0] : null
                });
            } catch (error) {
                results.push({
                    sortType,
                    success: false,
                    error: error.message
                });
            }
        }

        const resultsTable = results.map(result => `
                <div class="business-card">
                    <h3>${result.sortType}排序 ${result.success ? '✅' : '❌'}</h3>
                    ${result.success ? `
                        <p><strong>数据数量：</strong>${result.count}</p>
                        ${result.firstBusiness ? `
                            <p><strong>第一个商家：</strong>${result.firstBusiness.businessName}</p>
                            <p><strong>${result.sortType}值：</strong>${result.firstBusiness[result.sortType]}</p>
                        ` : ''}
                    ` : `
                        <p><strong>错误：</strong>${result.error}</p>
                    `}
                </div>
            `).join('');

        const successCount = results.filter(r => r.success).length;
        const status = successCount === results.length ? 'success' : 'error';

        showResult('businessResult', status,
            `📊 批量测试完成 (${successCount}/${results.length} 成功)`,
            resultsTable,
            results
        );

        setButtonState('testAllBtn', false);
    }

    // 检查商家表结构
    async function checkBusinessTable() {
        showLoading('databaseResult', '正在检查数据库表结构...');
        setButtonState('checkTableBtn', true);

        try {
            // 通过API获取数据来推断表结构
            const response = await fetch(`${API_BASE}/api/BusinessController/listBusiness`);
            const data = await response.json();

            if (response.ok && Array.isArray(data) && data.length > 0) {
                const firstBusiness = data[0];
                const fields = Object.keys(firstBusiness);
                const requiredFields = ['businessId', 'businessName', 'distance', 'monthlySales', 'rating'];
                const missingFields = requiredFields.filter(field => !fields.includes(field));

                const fieldsList = fields.map(field => `
                        <div class="detail-item">
                            <span class="detail-label">${field}:</span>
                            <span class="detail-value">${typeof firstBusiness[field]} (${firstBusiness[field]})</span>
                        </div>
                    `).join('');

                showResult('databaseResult', missingFields.length === 0 ? 'success' : 'error',
                    `🗄️ 表结构检查完成`,
                    `
                            <p><strong>数据记录数：</strong>${data.length}</p>
                            <p><strong>字段总数：</strong>${fields.length}</p>
                            ${missingFields.length > 0 ? `
                                <p><strong>⚠️ 缺失字段：</strong>${missingFields.join(', ')}</p>
                                <p><strong>建议：</strong>运行数据库迁移脚本添加缺失字段</p>
                            ` : `
                                <p><strong>✅ 所有必需字段都存在</strong></p>
                            `}
                            <h4>字段详情 (基于第一条记录):</h4>
                            <div class="business-details">${fieldsList}</div>
                        `,
                    { fields, missingFields, sampleData: firstBusiness }
                );
            } else {
                throw new Error('无法获取数据或数据为空');
            }
        } catch (error) {
            showResult('databaseResult', 'error',
                '❌ 表结构检查失败',
                `
                        <p><strong>错误：</strong>${error.message}</p>
                        <p><strong>可能原因：</strong></p>
                        <ul>
                            <li>数据库连接失败</li>
                            <li>business表不存在或为空</li>
                            <li>后端API服务异常</li>
                        </ul>
                    `,
                { error: error.message }
            );
        } finally {
            setButtonState('checkTableBtn', false);
        }
    }

    // 测试基础查询
    async function testBasicQuery() {
        showLoading('databaseResult', '正在测试基础查询...');
        setButtonState('testQueryBtn', true);

        try {
            const response = await fetch(`${API_BASE}/api/BusinessController/listBusiness`);
            const data = await response.json();

            if (response.ok && Array.isArray(data)) {
                // 计算统计信息
                const stats = {
                    total: data.length,
                    hasDistance: data.filter(b => b.distance && b.distance > 0).length,
                    hasSales: data.filter(b => b.monthlySales && b.monthlySales > 0).length,
                    hasRating: data.filter(b => b.rating && b.rating > 0).length,
                    avgDistance: (data.reduce((sum, b) => sum + (b.distance || 0), 0) / data.length).toFixed(2),
                    avgSales: Math.round(data.reduce((sum, b) => sum + (b.monthlySales || 0), 0) / data.length),
                    avgRating: (data.reduce((sum, b) => sum + (b.rating || 0), 0) / data.length).toFixed(1)
                };

                showResult('databaseResult', 'success',
                    '📈 基础查询统计',
                    `
                            <div class="business-details">
                                <div class="detail-item">
                                    <span class="detail-label">总商家数:</span>
                                    <span class="detail-value">${stats.total}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">有距离数据:</span>
                                    <span class="detail-value">${stats.hasDistance}/${stats.total}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">有销量数据:</span>
                                    <span class="detail-value">${stats.hasSales}/${stats.total}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">有评分数据:</span>
                                    <span class="detail-value">${stats.hasRating}/${stats.total}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">平均距离:</span>
                                    <span class="detail-value">${stats.avgDistance}km</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">平均销量:</span>
                                    <span class="detail-value">${stats.avgSales}单</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">平均评分:</span>
                                    <span class="detail-value">${stats.avgRating}分</span>
                                </div>
                            </div>
                            ${stats.hasDistance === 0 || stats.hasSales === 0 || stats.hasRating === 0 ? `
                                <p><strong>⚠️ 警告：</strong>部分排序字段数据缺失，这可能是排序不生效的原因</p>
                            ` : `
                                <p><strong>✅ 数据完整：</strong>所有排序字段都有数据</p>
                            `}
                        `,
                    { stats, sampleData: data.slice(0, 5) }
                );
            } else {
                throw new Error('查询返回数据格式错误');
            }
        } catch (error) {
            showResult('databaseResult', 'error',
                '❌ 基础查询失败',
                `<p><strong>错误：</strong>${error.message}</p>`,
                { error: error.message }
            );
        } finally {
            setButtonState('testQueryBtn', false);
        }
    }

    // 页面加载完成后自动测试连接
    window.addEventListener('load', function() {
        console.log('ELM API 调试工具已加载');
        // 可以在这里添加自动测试
    });
</script>
</body>
</html>